//网络请求的封装

import 'package:dio/dio.dart';
// import 'package:flutter/material.dart';
import 'package:flutter_community/utils/eventBus.dart';
import 'package:flutter_community/utils/preference.dart';

class NetWorkService {
  //dio实例
  final _dio = Dio();
  NetWorkService() {
    //配置基地址
    _dio.options.baseUrl = "https://live-api.itheima.net";
    //连接数据响应时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    //接收数据超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    _dio.options.headers = {'Content-Type': 'application/json'};
    //添加拦截器
    _addInterceptors();
  }

  //封装请求-get
  Future<dynamic> get(String url, {Map<String, dynamic>? params}) async {
    try {
      final response = await _dio.get(url, queryParameters: params);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  //封装请求-post
  Future<dynamic> post(String url, {dynamic data}) async {
    try {
      final response = await _dio.post(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  //封装请求-put
  Future<dynamic> put(String url, {Map<String, dynamic>? data}) async {
    try {
      final response = await _dio.put(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  //封装请求-delete
  Future<dynamic> delete(String url, {Map<String, dynamic>? data}) async {
    try {
      final response = await _dio.delete(url, data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

//拦截器
  void _addInterceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        // 请求拦截器：添加公共请求参数、token 等
        // 1.获取token
        final token = TokenManager().getToken() ?? '';
        if (token.isNotEmpty) {
          // 2.添加token
          options.headers['Authorization'] = 'Bearer $token';
        }

        return handler.next(options);
      },
      onResponse: (response, handler) {
        // 响应拦截器：统一处理成功响应
        return handler.next(response);
      },
      onError: (DioException error, handler) {
        // 响应拦截器：统一处理错误响应
        return handler.next(error);
      },
    ));
  }

//响应失败处理
  dynamic handleResponse(Response response) {
    if (response.statusCode! >= 200 && response.statusCode! < 300) {
      return response.data;
    } else {
      throw Exception('请求失败，状态码：${response.statusCode}');
    }
  }

  //错误处理
  dynamic handleError(error) {
    if (error is DioException) {
      if (error.type == DioExceptionType.connectionTimeout ||
          error.type == DioExceptionType.receiveTimeout) {
        throw Exception('网络连接超时');
      } else if (error.type == DioExceptionType.badResponse) {
        //token失效处理
        if (error.response?.statusCode == 401) {
          // 401错误处理
          // 1.清除token
          TokenManager().removeToken();
          // 2.跳转到登录页面->由于使用Navigator获取不到上下文,因此改用eventBus进行跳转
          //发送指令
          eventBus.fire(LogoutEvent());
        } else {
          throw Exception('响应错误,状态码: ${error.response?.statusCode}');
        }
      } else {
        throw Exception('网络请求错误:$error');
      }
    } else {
      throw Exception('未知错误：$error');
    }
  }
}

final http = NetWorkService();
